<?php

namespace Swostar\Routes;

class Route  
{
    protected static $instance = null;

    // 路由文件集合
    protected $routeMap = [];

    // 路由存储
    protected $routes = [];

    // 访问类型
    protected static $verbs = ['GET', 'POST', 'PUT', 'DELETE'];

    public function __construct()
    {
        // 包含路由文件
        $this->routeMap = [
            'Http' => app()->getBasePath() . DS . 'route' . DS . 'http.php'
        ];
    }

    public static function getInstance()
    {
        if (is_null(self::$instance)) {
            self::$instance = new static();
        }
        return self::$instance;
    }

    public static function get($uri, $action)
    {
        return $this->addRoute(['GET'], $uri, $action);
    }

    public static function post($uri, $action)
    {
        return $this->addRoute(['POST'], $uri, $action);
    }

    public static function any($uri, $action)
    {
        return $this->addRoute(self::$verbs, $uri, $action);
    }

    /**
     * 注册路由
     * @param array $methods 请求方式
     * @param string $uri 地址
     * @param mixed $action 执行方法
     * @return $this 
     */
    protected function addRoute(array $methods, string $uri, $action)
    {
        foreach ($methods as $method) {
            $this->routes[$method][$uri] = $action;
        }
        return $this;
    }

    public function registerRoute()
    {
        foreach ($this->routeMap as $key => $path) {
            require_once $path;
        }
        return $this;
    }

    public function getRoutes()
    {
        return $this->routes;
    }
}
